import DataProcess
import datetime
import Core.Config as Config
import Core.Gadget as Gadget
import Core.MySQLDB as MySQLDB
import numpy as np


def CodeToSymbol(code):
    if code[0] == "0" or "2":
        return code + ".SZ"
    if code[0] == "6":
        return code + ".SH"
    return None


# 储存滚动预测值为因子
# 只用预测的绝对值
# con or yoy roll （Operating Revenue YoY）
# con np yoy roll （Net Profit YoY）
def Analyst_ConsensusForecast_Rolling(fromDatabase, toDatabase, fieldName, factorName, datetime1=None, datetime2=None):
    filter={}
    if datetime1 != None and datetime2 != None:
        filter["DateTime"] = {">=": datetime1, "<=": datetime2}

    #
    count = fromDatabase.Count("goaldb", "con_forecast_roll_stk", filter=filter)
    batchSize = 1000
    batchCount = int(count / batchSize) + 1

    filter = {}
    filter["limit"] = batchSize
    #
    for i in range(batchCount):
        print(i, "of", batchCount, datetime.datetime.now())
        if i < 4500:
          continue
        filter["skip"] = i * batchSize
        documents = fromDatabase.Find("goaldb", "con_forecast_roll_stk",
                                      filter=filter,
                                      projection=["id", "stock_code", "con_date", fieldName])
        #
        newDocuments = []
        for doc in documents:
            newDocument = {}
            # 原版Code没有交易所后缀
            symbol = CodeToSymbol(doc["stock_code"])
            if symbol == None:
                print(doc["stock_code"])
                continue
            newDocument["Symbol"] = symbol
            newDocument["Value"] = doc[fieldName]
            #
            conDate = doc["con_date"]
            newDocument["DateTime"] = datetime.datetime(conDate.year, conDate.month, conDate.day)
            newDocument["Date"] = doc["con_date"]
            newDocument["UTCDateTime"] = Gadget.ToUTCDateTime(newDocument["DateTime"])
            #
            reportDate = Gadget.FindReportDate(newDocument["DateTime"])
            newDocument["ReportDate"] = reportDate
            newDocument["Period"] = Gadget.ReportPeriod(reportDate)
            newDocument["Key2"] = symbol + "_" + Gadget.ToDateTimeString(newDocument["DateTime"])
            #
            newDocuments.append(newDocument)
        #
        toDatabase.Upsert_Many("Factor", factorName, [], newDocuments)
        pass

    #


# 储存预测值为因子
# 用预测值和当期值的差值
# con or roll （Operating Revenue）
# con np roll （Net Profit）
# con eps roll
# con pe roll
# con pb roll
def Analyst_ConsensusForecast_Rolling_Diff(fromDatabase, toDatabase, fieldName, factorName, datetime1, datetime2):
    pass


def Analyst_ConsensusForecast(fromDatabase, toDatabase, fieldName, factorName, datetime1, datetime2):
    pass


def Analyst_ConsensusForecast_Diff(fromDatabase, toDatabase, fieldName, factorName, datetime1, datetime2):
    pass


if __name__ == '__main__':
    #
    config = Config.Config()
    toDatabase = config.DataBase("MySQL")

    # ---Connect zhao yang yong xu Database---
    fromDatabase = MySQLDB.MySQLDB("172.25.4.214", "3306",
                                    username="m_goaldb",
                                    password="ucOTRY")
    #
    # Analyst_ConsensusForecast_Rolling(fromDatabase, toDatabase,
    #                                   fieldName="con_or_yoy_roll",
    #                                   factorName="Analyst_Con_OR_YoY_Roll",
    #                                   datetime1=None,
    #                                   datetime2=None)

    Analyst_ConsensusForecast_Rolling(fromDatabase, toDatabase,
                                      fieldName="con_np_yoy_roll",
                                      factorName="Analyst_Con_NP_YoY_Roll",
                                      datetime1=None,
                                      datetime2=None)
